import { getMySQLPool, testMySQLConnection } from '../database/mysql';
import { testRedisConnection } from '../database/redis';
import config from '../config';

/**
 * ANSI 颜色代码
 */
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  dim: '\x1b[2m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m',
  white: '\x1b[37m',
  bgGreen: '\x1b[42m',
  bgRed: '\x1b[41m',
  bgCyan: '\x1b[46m',
};

/**
 * 打印模块信息（简洁版）
 */
function printModule(
  title: string,
  icon: string,
  status: 'success' | 'error' | 'info',
  content: string[]
): void {
  const statusColor = status === 'success' ? colors.green : status === 'error' ? colors.red : colors.cyan;
  const statusIcon = status === 'success' ? '✓' : status === 'error' ? '✗' : '○';
  const statusText = status === 'success' ? '正常' : status === 'error' ? '失败' : '检查中';
  
  // 标题行
  console.log(
    '  ' +
    colors.cyan + colors.bright + icon + ' ' + title + colors.reset +
    colors.dim + ' · ' + colors.reset +
    statusColor + statusIcon + ' ' + statusText + colors.reset
  );
  
  // 内容行
  content.forEach((line) => {
    console.log('    ' + line);
  });
  
  console.log(); // 空行
}

/**
 * 打印主标题
 */
function printMainTitle(): void {
  console.log();
  console.log(
    colors.cyan + colors.bright + '🚀 Koa Admin Template - 服务启动检查' + colors.reset
  );
  console.log(colors.dim + '─'.repeat(50) + colors.reset);
  console.log();
}

/**
 * 检查 MySQL 连接状态并获取详细信息
 */
export async function checkMySQLStatus(): Promise<{
  connected: boolean;
  version?: string;
  database?: string;
  host?: string;
  port?: number;
  error?: string;
}> {
  try {
    const pool = getMySQLPool();
    
    // 测试连接
    const isConnected = await testMySQLConnection();
    
    if (!isConnected) {
      return {
        connected: false,
        error: '连接测试失败',
      };
    }
    
    // 获取 MySQL 版本
    const [versionRows] = await pool.execute('SELECT VERSION() as version');
    const version = (versionRows as any[])[0]?.version || 'Unknown';
    
    return {
      connected: true,
      version,
      database: config.mysql.database,
      host: config.mysql.host,
      port: config.mysql.port,
    };
  } catch (error: any) {
    return {
      connected: false,
      error: error?.message || '未知错误',
    };
  }
}

/**
 * 检查 Redis 连接状态并获取详细信息
 */
export async function checkRedisStatus(): Promise<{
  connected: boolean;
  host?: string;
  port?: number;
  db?: number;
  error?: string;
}> {
  try {
    // 测试连接
    const isConnected = await testRedisConnection();
    
    if (!isConnected) {
      return {
        connected: false,
        error: '连接测试失败',
      };
    }
    
    // 连接成功，返回配置信息
    return {
      connected: true,
      host: config.redis.host,
      port: config.redis.port,
      db: config.redis.db,
    };
  } catch (error: any) {
    return {
      connected: false,
      error: error?.message || '未知错误',
    };
  }
}

/**
 * 启动时检查服务状态
 */
export async function startupCheck(): Promise<boolean> {
  printMainTitle();
  
  let allSuccess = true;
  
  // 检查 MySQL
  const mysqlStatus = await checkMySQLStatus();
  const mysqlContent: string[] = [];
  
  if (mysqlStatus.connected) {
    mysqlContent.push(
      colors.dim + '地址: ' + colors.reset + colors.white + `${mysqlStatus.host}:${mysqlStatus.port}` + colors.reset
    );
    mysqlContent.push(
      colors.dim + '数据库: ' + colors.reset + colors.white + (mysqlStatus.database || 'Unknown') + colors.reset
    );
    mysqlContent.push(
      colors.dim + '版本: ' + colors.reset + colors.white + (mysqlStatus.version || 'Unknown') + colors.reset
    );
    printModule('MySQL 数据库', '🗄️', 'success', mysqlContent);
  } else {
    mysqlContent.push(
      colors.dim + '地址: ' + colors.reset + colors.white + `${config.mysql.host}:${config.mysql.port}` + colors.reset
    );
    mysqlContent.push(
      colors.dim + '数据库: ' + colors.reset + colors.white + config.mysql.database + colors.reset
    );
    if (mysqlStatus.error) {
      mysqlContent.push(
        colors.dim + '错误: ' + colors.reset + colors.red + mysqlStatus.error + colors.reset
      );
    }
    printModule('MySQL 数据库', '🗄️', 'error', mysqlContent);
    allSuccess = false;
  }
  
  // 检查 Redis
  const redisStatus = await checkRedisStatus();
  const redisContent: string[] = [];
  
  if (redisStatus.connected) {
    redisContent.push(
      colors.dim + '地址: ' + colors.reset + colors.white + `${redisStatus.host}:${redisStatus.port}` + colors.reset
    );
    redisContent.push(
      colors.dim + '数据库: ' + colors.reset + colors.white + `DB ${redisStatus.db || 0}` + colors.reset
    );
    printModule('Redis 缓存', '⚡', 'success', redisContent);
  } else {
    redisContent.push(
      colors.dim + '地址: ' + colors.reset + colors.white + `${config.redis.host}:${config.redis.port}` + colors.reset
    );
    redisContent.push(
      colors.dim + '数据库: ' + colors.reset + colors.white + `DB ${config.redis.db}` + colors.reset
    );
    if (redisStatus.error) {
      redisContent.push(
        colors.dim + '错误: ' + colors.reset + colors.red + redisStatus.error + colors.reset
      );
    }
    printModule('Redis 缓存', '⚡', 'error', redisContent);
    // Redis 失败不阻止启动，只警告
  }
  
  // 打印服务器信息模块
  const serverContent: string[] = [];
  serverContent.push(
    colors.dim + '端口: ' + colors.reset + colors.white + config.port + colors.reset
  );
  serverContent.push(
    colors.dim + '环境: ' + colors.reset + 
    (config.env === 'prd' ? colors.red : colors.green) + 
    config.env.toUpperCase() + colors.reset
  );
  printModule('服务器信息', '🌐', 'info', serverContent);
  
  // 总结
  console.log(colors.dim + '─'.repeat(50) + colors.reset);
  if (!allSuccess) {
    console.log(
      colors.red + colors.bright + 
      '⚠️  警告: 部分服务连接失败，可能影响系统正常运行！' + 
      colors.reset
    );
  } else {
    console.log(
      colors.green + colors.bright + 
      '✓ 所有服务检查完成，系统准备就绪！' + 
      colors.reset
    );
  }
  console.log();
  
  return allSuccess;
}

